#ifndef __AX_IIC_H
#define __AX_IIC_H
#include "ax_sys.h"
#define  my_iic_stop(SCL,SDA,dy)  {SCL=0;SDA=0; dy();SCL=1;dy(); SDA=1;dy(); }
#define  my_iic_start(SCL,SDA,READ,dy)   {SDA=1; dy();if(!READ){return 1;} SCL=1; dy(); SDA=0; dy();  if(READ){  return 2;  }  SCL=0;  return 0;  }

#define  my_iic_send_ask(SCL,SDA,READ,dy) { SDA=1;dy();SCL=1;dy();if(READ){ return 3;}  SCL=0;return 0; }
#define  my_iic_send_byte( data,SCL,SDA,READ,dy) {uint8_t t;    SCL=0; for(t=0; t<8; t++) {SDA=(data&0x80)>>7;dy(); SCL=1;  dy();  SCL=0; data<<=1; }my_iic_send_ask(SCL,SDA,READ,dy); }
   
#define  my_iic_read_ask(SCL,SDA,dy,ack)   {dy();SCL=0; dy();SDA=(ack==0?1:0); dy();SCL=1;dy();SCL=0;  } 
#define  my_iic_read(SCL,SDA,READ,dy,ack)  {uint8_t  r=0;dy();for(int8_t i=0;i<8;i++ ) {  r<<=1;SCL=0;dy();SCL=1; dy();  if(READ){  r++; }  }my_iic_read_ask(SCL,SDA,dy,ack);  return r;}    

    
#define MY_IIC_Addr(addr0,addr1,start,send)   addr0=addr0 << 1;my_err(10,start());my_err(20,send(addr0));my_err(30,send(addr1));
    
#define MY_IIC_test(addr0 ,start,send,stop){ addr0=addr0 << 1; my_err(10,start()); if (send(addr0)){ stop(); return 50; }else{  stop(); return 60;}  }
#define MY_IIC_Write(addr0,addr1, len, data,start,send,stop)  {     MY_IIC_Addr(addr0,addr1,start,send);for (int i = 0; i < len; i++){ my_err(40,send(data[i])); }stop();  return 0;  }
#define MY_IIC_Write_byte(addr0,addr1,data,start,send,stop)   {      MY_IIC_Addr(addr0,addr1,start,send);  my_err(40,send(data));stop(); return 0; }
#define MY_IIC_Read(addr0, addr1, len,data,start,send,Read,stop)  {  MY_IIC_Addr(addr0,addr1,start,send);  my_err(10,start());  my_err(20,send(addr0+1));  while (len){  if (len == 1){ *data = Read(0);} else{*data = Read(1);} data++; len--; }  stop(); return 0; }   
#define MY_IIC_Read_byte(addr0,   addr1,   data,start,send,Read,stop){MY_IIC_Addr(addr0,addr1,start,send);   my_err(10,start());  my_err(20,send(addr0+1)); *data = Read(0);  stop();  return 0; }
#endif 
